package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sql.DBManagment;
import sql.record.TableRecord;
import sql.record.User;

/**
 * Servlet implementation class profile
 */
public class profile extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public profile() {
		super();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		User updatingUser = new User();
		// getting data from form
		updatingUser.userName = (String) request.getSession().getAttribute(
				"loggedUser");
		updatingUser.surName = request.getParameter("surName");
		updatingUser.givenName = request.getParameter("givenName");
		updatingUser.phoneNumber = request.getParameter("phoneNumber");
		updatingUser.password = request.getParameter("password1");
		PrintWriter out = response.getWriter();
		try {
			List<User> uList = DBManagment.getRecord(updatingUser);
			User storedUser = uList.get(0);
			if (updatingUser.password.equals("")) {
				updatingUser.password = storedUser.password;
			}
			updatingUser.type = storedUser.type;
		} catch (Exception e) {
			out.print("<firefoxsucks>notupdated</firefoxsucks>");
			// TODO:generate some error page....
		}

		// updating in DB
		List<TableRecord> regList = new LinkedList<TableRecord>();
		regList.add(updatingUser);
		try {
			// inserting to DB
			DBManagment.updateRecord(regList);
			// output
			out.print("<firefoxsucks>updated</firefoxsucks>");
		} catch (Exception e) {
			// output
			out.print("<firefoxsucks>notupdated</firefoxsucks>");
		}
		out.close();
	}
}
